//
//  connectCreateWifiVController.m
//  SKaURobot
//
//  Created by cdong on 16/2/25.
//  Copyright © 2016年 cdong. All rights reserved.
//

#import "connectCreateWifiVController.h"
#import "connectCreateWifiView.h"
#import "KMQRCode.h"
#import "UIImage+RoundedRectImage.h"
#import "AFHTTPSessionManager.h"
#import "SKFirstVController.h"
#import "connectRobotWifiVController.h"

@interface connectCreateWifiVController ()

@property (nonatomic ,strong)connectCreateWifiView *createQRV;
@property (nonatomic ,strong)NSTimer *timer;
@property (nonatomic ,strong)NSTimer *timerOut;

@end

@implementation connectCreateWifiVController

- (void)loadView{
    self.createQRV = [[connectCreateWifiView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.view = self.createQRV;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

// 请求超时 停止
static NSInteger requestTime = 1;

// 返回
- (void)backBtnAction:(UIButton *)sender{
    requestTime = 1;
    [self.timer invalidate];
    self.timer = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    [self.createQRV.backBtn addTarget:self action:@selector(backBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self handleData];
    [self createQR];
}

#pragma 请求超时的时间待定
- (void)requestAction{
    requestTime ++;
    if (requestTime > 6) { // 请求超时的时间待定
        [self.timer invalidate];
        self.timer = nil;
        [self alertReminderMessage:@"绑定失败"];
        requestTime = 1;
//        connectRobotWifiVController *connect = [[connectRobotWifiVController alloc]init];
//        [self.navigationController pushViewController:connect animated:YES];
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"绑定失败" message:@"" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault
//            handler:^(UIAlertAction * _Nonnull action) {
//                requestTime = 1;
//                connectRobotWifiVController *connect = [[connectRobotWifiVController alloc]init];
//                [self.navigationController pushViewController:connect animated:YES];
//        }];
//        [alertController addAction:okAction];
//        [self presentViewController:alertController animated:YES completion:nil];
    }
    NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
    NSString *uid = [dd objectForKey:@"uid"];
    NSString *sesskey = [dd objectForKey:@"sesskey"];
    NSString *urlStr = [NSString stringWithFormat:@"http:///api.au-smart.cn/index.php?act=getStatus&uid=%@&sesskey=%@",uid,sesskey];
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"sn  %@",responseObject);
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        NSString *sn = [responseObject objectForKey:@"sn"];
        if (error.integerValue == 0 && sn != nil) {
            [self.timer invalidate];
            self.timer = nil;
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"绑定成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                SKFirstVController *firstVC = [[SKFirstVController alloc]init];
                firstVC.updateUIFlag = YES;
                [self.navigationController pushViewController:firstVC animated:YES];
            }];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
//            [self alertReminderMessage:@"绑定成功"];
//            SKFirstVController *firstVC = [[SKFirstVController alloc]init];
//            firstVC.updateUIFlag = YES;
//            [self.navigationController pushViewController:firstVC animated:YES];
        }else{
            /*
            [self.timer invalidate];
            self.timer = nil;
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"绑定失败" message:@"" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault
                handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
//            [self alertReminderMessage:@"绑定失败"];
//            if (errorCode.integerValue == 1036) {
//                [self alertReminderMessage:@"未连接机器人"];
//            }else{
//                [self alertReminderMessage:@"绑定失败"];
//            }*/
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)handleData{
    NSUserDefaults *defualts = [NSUserDefaults standardUserDefaults];
    NSString *uid = [defualts objectForKey:@"uid"];
    NSString *sesskey = [defualts objectForKey:@"sesskey"];
    NSLog(@"扫描 %@",sesskey);
    NSString *urlStr = [NSString stringWithFormat:@"http://api.au-smart.cn/index.php?act=robotUserinfo&uid=%@&sesskey=%@",uid,sesskey];
    NSLog(@"erweimaURL  %@",urlStr);
    NSString *utf = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:utf parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"二维码生成 %@",responseObject);
        NSNumber *error = [responseObject objectForKey:@"error"];
        NSNumber *errorCode = [responseObject objectForKey:@"errorCode"];
        NSString *user_name = [responseObject[@"info_list"][0] objectForKey:@"user_name"];
        NSString *avatar = [responseObject[@"info_list"][0] objectForKey:@"avatar"];
        if (error.integerValue == 0) {
            UIImage *icon = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:avatar]]];
            self.createQRV.iconImageV.image = icon;
            self.createQRV.userNameL.text = user_name;
        }else{
            if (errorCode.integerValue == 1035) {
                [self alertReminderMessage:@"用户未登录"];
            }else{
                [self alertReminderMessage:@"用户未登录"];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

// 提示弹框
- (void)alertReminderMessage:(NSString *)message
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 二维码加密
- (NSString *)encryptionWithString:(NSString *)sString{
    NSString *newStr = sString;
    NSString *resultStr = @"";
    for(int i = 0; i < [newStr length]; i++)
    {
        int c = [newStr characterAtIndex:i];
        if(c >= 0x4E00 && c <= 0x9FFF){
            NSRange range = {i,1};
            NSString *ss = [newStr substringWithRange:range];
            resultStr = [NSString stringWithFormat:@"%@%@",resultStr,ss];
            continue;
        }else if (c >= 48 && c <= 57) {
            char mm = 105 - c;
            resultStr = [NSString stringWithFormat:@"%@%c",resultStr,mm];
        }else if (c >= 97 && c <= 122){
            c = 219 - c;
            resultStr = [NSString stringWithFormat:@"%@%c",resultStr,c];
        }else if (c >= 65 && c <= 90){
            c = 155 - c;
            resultStr = [NSString stringWithFormat:@"%@%c",resultStr,c];
        }else{
            resultStr = [NSString stringWithFormat:@"%@%c",resultStr,c];
        }
    }
    return resultStr;
}


- (void)createQR{
    
    // 二维码清晰度保持方法
    // 用于生成二维码的字符串wifiStr
    NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
    NSString *wifiName = [dd objectForKey:@"CurrentWifiName"];// @"Interjoy_mobile"; //
    NSString *wifiPwd = [dd objectForKey:@"CurrentWifiPwd"]; // @"20050805";//
    NSString *uid = [dd objectForKey:@"uid"];
//    NSString *wifiStr = [NSString stringWithFormat:@"sk%@[]||-%@",wifiName,wifiPwd];
    NSString *wifiStr = [NSString stringWithFormat:@"sk%@[]||-%@[]||-%@",wifiName,wifiPwd,uid];
    wifiStr = [self encryptionWithString:wifiStr];
    // 使用iOS 7后的CIFilter对象操作，生成二维码图片imgQRCode（会拉伸图片，比较模糊，效果不佳）
    CIImage *imgQRCode = [KMQRCode createQRCodeImage:wifiStr];

    // 使用核心绘图框架CG（Core Graphics）对象操作，进一步针对大小生成二维码图片imgAdaptiveQRCode（图片大小适合，清晰，效果好）
   UIImage *imgAdaptiveQRCode = [KMQRCode resizeQRCodeImage:imgQRCode                                                   withSize: self.createQRV.QRCodeImageV.frame.size.width];

    // 默认产生的黑白色的二维码图片；我们可以让它产生其它颜色的二维码图片，例如：蓝白色的二维码图片
    // imgAdaptiveQRCode = [KMQRCode specialColorImage:imgAdaptiveQRCode withRed:33.0                                             green:114.0                             blue:237.0]; //0~255
    // 使用核心绘图框架CG（Core Graphics）对象操作，创建带圆角效果的图片
    // UIImage *imgIcon = [UIImage createRoundedRectImage:[UIImage imageNamed:@"QRCode"]                                             withSize:CGSizeMake(70.0, 93.0)                                            withRadius:10];
    // 使用核心绘图框架CG（Core Graphics）对象操作，合并二维码图片和用于中间显示的图标图片
    // imgAdaptiveQRCode = [KMQRCode addIconToQRCodeImage:imgAdaptiveQRCode withIcon:imgIcon withIconSize:imgIcon.size];
  
    // imgAdaptiveQRCode = [KMQRCode addIconToQRCodeImage:imgAdaptiveQRCode withIcon:imgIcon withScale:3];
    self.createQRV.QRCodeImageV.image = imgAdaptiveQRCode;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(requestAction) userInfo:nil repeats:YES];
    
    // 模糊不清晰
    /*
//    // 1.实例化二维码滤镜
//    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//    
//    // 2.恢复滤镜的默认属性 (因为滤镜有可能保存上一次的属性)
//    [filter setDefaults];
//    
//    // 3.将字符串转换成NSdata
//    NSUserDefaults *dd = [NSUserDefaults standardUserDefaults];
//    NSString *wifiName = [dd objectForKey:@"CurrentWifiName"];
//    NSString *wifiPwd = [dd objectForKey:@"CurrentWifiPwd"];
//    NSString *wifiStr = [NSString stringWithFormat:@"%@,%@",wifiName,wifiPwd];
//    NSData *data  = [wifiStr dataUsingEncoding:NSUTF8StringEncoding];
//    
//    // 4.通过KVO设置滤镜, 传入data, 将来滤镜就知道要通过传入的数据生成二维码
//    [filter setValue:data forKey:@"inputMessage"];
//    
//    // 5.生成二维码
//    CIImage *outputImage = [filter outputImage];
//    UIImage *image = [UIImage imageWithCIImage:outputImage];
//    
//    // 6.设置生成好得二维码到imageview上
//    self.createQRV.QRCodeImageV.image = image;
     */
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
